package com.course.server.service.impl;


import com.course.server.entity.dto.UserTokenDTO;
import com.course.server.entity.po.AdminUser;
import com.course.server.entity.vo.LoginVO;
import com.course.server.mapper.AdminUserMapper;
import com.course.server.service.RedisService;
import com.course.server.service.AdminUserService;
import com.course.server.utils.JWTUtil;
import com.course.server.utils.ResponseResult;
import com.course.server.utils.ResponseStatus;
import com.course.server.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminUserServiceImpl implements AdminUserService {
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public Result<Map<String,Object>> login(LoginVO loginVO) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        //1.判断用户名密码是否正确
        AdminUser user = adminUserMapper.selectByUserName(loginVO.getUsername());
        if (user == null) {
            log.info("用户不存在");
            return Result.fail(null,ResponseStatus.HTTP_STATUS_404.getResponseCode(),"用户不存在");

        }
        if (!loginVO.getPassword().equals(user.getPassword())) {
            log.info("密码不匹配");
            return Result.fail(null,ResponseStatus.HTTP_STATUS_403.getResponseCode(),"密码不匹配");
        }

        //2.用户名密码正确生成token
        UserTokenDTO userTokenDTO = new UserTokenDTO();
        PropertyUtils.copyProperties(userTokenDTO, loginVO);
        userTokenDTO.setId(user.getUserId());
        userTokenDTO.setGmtCreate(System.currentTimeMillis());
        String token = JWTUtil.generateToken(userTokenDTO);

        //3.存入token至redis
        redisService.set(String.valueOf(user.getUserId()), token);

        log.info("登陆成功：返回token: {}" ,token);
        Map<String,Object> result = new HashMap<>();
        result.put("token", token);
        return Result.ok(result);
    }

    @Override
    public ResponseResult<Boolean> loginOut(String token) {
        UserTokenDTO userTokenDTO = JWTUtil.parseToken(token);
        boolean result = redisService.delete(String.valueOf(userTokenDTO.getId()));
        if (!result) {
             return ResponseResult.fail(false);
        }

        return ResponseResult.success(true,"退出登陆成功");
    }
}
